Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Inheritance Concept

Inheriting constructors

In Java’s Object-Oriented Programming (OOP), constructors are special methods used to initialize the state of an object. However, constructors are not considered members of a class, and only members are inherited. Therefore, constructors are not directly inherited by subclasses. Here’s an example:
Inheriting a constructor in java class Base { Base() { System.out.println("Base Class Constructor Called"); } } class Derived extends Base { Derived() { System.out.println("Derived Class Constructor Called"); } } public class Main { public static void main(String[] args) { Derived d = new Derived(); } }

Output

animal is created dog is created
In this example, when an object of the Derived class is created, the constructor of the Base class is called first, followed by the constructor of the Derived class. This is because in Java, the constructor of the base class with no argument gets automatically called in the derived class constructor. However, if you want to call a parameterized constructor of the base class, you can do so using the super keyword. The super keyword in Java is a reference variable that is used to refer to the immediate parent class object1. It must be the first statement in the derived class constructor. Here’s an example:
Calling a parameterized constructor using super keyword class Base { int x; Base(int _x) { x = _x; } } class Derived extends Base { int y; Derived(int _x, int _y) { super(_x); y = _y; } void Display() { System.out.println("x = " + x + ", y = " + y); } } public class Main { public static void main(String[] args) { Derived d = new Derived(10, 20); d.Display(); } }

Output

animal is created dog is created
In this example, super(_x) is used in the Derived class constructor to call the Base class constructor. This allows the Derived class to initialize the x variable in the Base class.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance ★ inheritance example ★extends ★ Method overriding ★super ★keyword

Tutorials